﻿using System;
using System.Windows.Forms;
using SourceCodePlugin.Collections;
using WindowsLive.Writer.Api;

namespace SourceCodePlugin.Controls
{
    public partial class SettingsEditor : SmartContentEditor
    {
        private Settings settings;
        private ISmartContent content;

        public SettingsEditor()
        {
            InitializeComponent();
            SetupTabSizeList();
            SetupLanguageList();

            SelectedContentChanged += new EventHandler(SettingsEditor_SelectedContentChanged);

            editButton.Click += new EventHandler(editButton_Click);
            saveButton.Click += new EventHandler(saveButton_Click);
        }

        void editButton_Click(object sender, EventArgs e)
        {
            using (var editor = new SourceCodeEditor(settings))
            {
                var result = editor.ShowDialog();
                if (result == DialogResult.OK)
                {
                    tabSizeList.SelectedValue = settings.TabSize;
                    languageList.SelectedValue = settings.Language;

                    OnContentEdited();
                }
            }
        }

        void saveButton_Click(object sender, EventArgs e)
        {
            var tabSize = (int)tabSizeList.SelectedValue;
            var language = (string)languageList.SelectedValue;

            if (tabSize.Equals(settings.TabSize) && language.Equals(settings.Language, StringComparison.Ordinal))
                return;

            var code = settings.Code;
            if (!tabSize.Equals(settings.TabSize))
                code = code.Indent(settings.TabSize, tabSize);

            settings.Code = code;
            settings.TabSize = tabSize;
            settings.Language = language;

            OnContentEdited();
        }

        void SettingsEditor_SelectedContentChanged(object sender, EventArgs e)
        {
            this.content = SelectedContent;
            this.settings = new Settings(content.Properties);

            this.tabSizeList.SelectedValue = settings.TabSize;
            this.languageList.SelectedValue = settings.Language;
        }

        void SetupTabSizeList()
        {
            tabSizeList.DataSource = TabSizeCollection.TabSizes;
            tabSizeList.DisplayMember = "Name";
            tabSizeList.ValueMember = "Value";
        }

        void SetupLanguageList()
        {
            languageList.DataSource = LanguageCollection.Languages;
            languageList.DisplayMember = "Name";
            languageList.ValueMember = "Value";
        }
    }
}
